<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Upload extends Base_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->load->model('attachs_m');
        if (!$this->auth->is_login()) {
            die('无权访问此页');
        }
    }

    /**
     * 后台通用上传
     * @author fengchen@addcn.com
     * @date   2019/9/9
     */
    public function do_upload()
    {
        $type                    = $this->input->get('type', true);
        $config['upload_path']   = FCPATH . 'uploads/' . $type . '/' . date("Ymd") . "/";
        $config['allowed_types'] = 'gif|jpg|png';
        $config['encrypt_name']  = true;
        $config['max_size']      = 3000;
        if (!file_exists($config['upload_path'])) {
            mkdir($config['upload_path'], 0777, true);
        }
        $this->load->library('upload', $config);
        if (!$this->upload->do_upload('file')) {
            echo json_encode([
                'status' => 4,
                'msg'    => '图片上传失败',
            ]);
            exit();
        }
        $upload_data = $this->upload->data();
        $url         = base_url('uploads/' . $type . '/' . date("Ymd") . '/' . $upload_data['file_name']);
        $arr         = [
            'status' => 1,
            'msg'    => '图片上传成功',
            'url'    => $url,
        ];
        echo json_encode($arr);
        exit();
    }

    /**
     * 删除图片
     * [deltet_img id]
     * @return [type] [description]
     */
    public function delete_img()
    {
        $attach_id = $this->input->post('key', true);
        $url       = $this->input->get('url', true);
        $filePath  = parse_url($url);
        if ($attach_id) {
            if (file_exists(FCPATH . $filePath['path'])) {
                unlink(FCPATH . $filePath['path']);
            }
            $arr = ['status' => 1, 'msg' => '图片删除成功'];
            echo json_encode($arr);
            exit;
        } else {
            return false;
        }
    }
}
